import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'dart:ui' as ui;

/// 保存绘图
class SaveCanvasPage extends StatefulWidget {
  const SaveCanvasPage({Key? key}) : super(key: key);

  @override
  State<SaveCanvasPage> createState() => _SaveCanvasPageState();
}

class _SaveCanvasPageState extends State<SaveCanvasPage>
    with SingleTickerProviderStateMixin {
  final ShapePainter _painter = ShapePainter();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: createCanvas,
        child: const Icon(Icons.save),
      ),
      body: Center(
        child: CustomPaint(
          size: const Size(100, 100),
          painter: _painter,
        ),
      ),
    );
  }

  void createCanvas() async {
    ui.PictureRecorder recorder = ui.PictureRecorder();
    Canvas canvas = Canvas(recorder);
    Size boxSize = const Size(100, 100);
    _painter.paint(canvas, boxSize);
    ui.Picture picture = recorder.endRecording();
    ui.Image image =
        await picture.toImage(boxSize.width.toInt(), boxSize.height.toInt());
    ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    if (byteData != null) {
      File file = File(r"/Users/yuan/Desktop/box.png");
      file.writeAsBytes(byteData.buffer.asUint8List());
    }
  }
}

class ShapePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()..color = Colors.blue;
    canvas.drawRect(Offset.zero & size, paint);
    paint
      ..style = PaintingStyle.stroke
      ..color = Colors.redAccent
      ..strokeWidth = 2;
    canvas.drawCircle(Offset(size.width / 2, size.height / 2), 40, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}
